package infraestructura;

import java.util.ArrayList;
import java.util.List;
import modelo.User;

public class UserMemoryPersistence implements UserPersistence {

    private List<User> users = new ArrayList<User>();
    private static UserMemoryPersistence persistence = null;
    
    private UserMemoryPersistence() {
        users.add(new User(1, "paco", "1234", "Paco Perez", "13 rue del percebe",
                true, "VISA", "1234567890123456789"));
    }
    
    public static UserPersistence getPersistenceManager() {
        if (persistence == null) {
            persistence = new UserMemoryPersistence();
        }
        return persistence;
    }
    
    @Override
    public boolean userExists(String username, String password) {
        for (User user : users) {
            if ((user.getUsername() == null ? username == null : user.getUsername().equals(username)) 
                    && (user.getPassword() == null ? password == null : user.getPassword().equals(password))) {
                return true;
            }
        }
        return false;
    }

    @Override
    public User getUser(String username, String password) {
        for (User user : users) {
            if ((user.getUsername() == null ? username == null : user.getUsername().equals(username)) 
                    && (user.getPassword() == null ? password == null : user.getPassword().equals(password))) {
                return user;
            }
        }
        throw new IllegalArgumentException("El usuario no existe. Debería validarse antes");
    }

    @Override
    public int createUser(User user) {
        users.add(user);
        return 0;
    }

    @Override
    public boolean userExists(String username) {
        for (User user : users) {
            if (user.getUsername() == null ? username == null : user.getUsername().equals(username)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public User getUser(int id) {
        for (User user : users) {
            if (user.getId() == id) {
                return user;
            }
        }
        throw new IllegalArgumentException("El usuario no existe. Debería validarse antes");
    }
    
}
